//
//  LGSportsPlanCreateController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/7/31.
//  运动方案--创建、编辑、复制

#import "LGSportsPlanCreateController.h"
//训练项目
#import "LGTrainingProgramController.h"

#import "LGRecoverySectionView.h"
#import "LGRecoverySportsInputCell.h"
#import "LGRecoverySportsProgramCell.h"
#import "LGPickerViewMax.h"
@interface LGSportsPlanCreateController ()<UITableViewDelegate,UITableViewDataSource,LGRecoverySportsInputCellDelegate,LGRecoverySportsProgramDelegate>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UIButton *addButton;
/**   */
@property (nonatomic , strong)UIButton *saveButton;
/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , strong)NSDictionary *keyDic;
/**   */
@property (nonatomic , strong)NSMutableDictionary *dataDic;

@end

@implementation LGSportsPlanCreateController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.keyDic = @{@"0":@"title",@"1":@"duration",@"2":@"frequency",@"3":@"description"};
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.saveButton];
    if(_planid && _planid.length>0){
        self.title = @"编辑运动方案";
        [self requestDetailData:self.planid];
        
    }else if (_copyid && _copyid.length>0){
        self.planid = @"";
        self.title = @"复制运动方案";
        [self requestDetailData:self.copyid];
        
    }else{
        self.planid = @"";
        self.title = @"创建运动方案";
    }
}

-(void)requestDetailData:(NSString *)dataid{
    [RequestUtil withPOST:@"/doctor/sport.plan/detail" parameters:@{@"plan_id":dataid} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            [self.dataDic setValue:LGNSString(returnData[@"title"]) forKey:@"title"];
            [self.dataDic setValue:LGNSString(returnData[@"duration"]) forKey:@"duration"];
            [self.dataDic setValue:LGNSString(returnData[@"frequency"]) forKey:@"frequency"];
            [self.dataDic setValue:LGNSString(returnData[@"description"]) forKey:@"description"];
            if (self.copyid && self.copyid.length>0){
                //名称+（副本）
                NSString *title = [NSString stringWithFormat:@"%@（副本）",returnData[@"title"]];
                [self.dataDic setValue:title forKey:@"title"];
                //复制--把训练id置为0
                NSArray *tempArray = returnData[@"actions"];
                for (NSInteger i=0; i<tempArray.count; i++) {
                    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:tempArray[i]];
                    NSMutableArray *itemArray = [NSMutableArray arrayWithArray:tempDic[@"items"]];
                    for (NSInteger j=0; j<itemArray.count; j++) {
                        NSMutableDictionary *itemDic = [NSMutableDictionary dictionaryWithDictionary:itemArray[j]];
                        [itemDic setValue:@"" forKey:@"id"];
                        [itemArray replaceObjectAtIndex:j withObject:itemDic];
                    }
                    [tempDic setValue:itemArray forKey:@"items"];
                    [self.dataArray addObject:tempDic];
                }
            }else{
                self.dataArray = [NSMutableArray arrayWithArray:returnData[@"actions"]];
            }
            [self.tableView reloadData];
        }
    } error:^(NSError *error) {
        
    }];
}

//添加训练
-(void)addButtonAction{
    LGTrainingProgramController *controller = [[LGTrainingProgramController alloc]init];
    [self.navigationController pushViewController:controller animated:YES];
    __weak typeof(self) weakSelf = self;
    controller.addTrainingData = ^(NSDictionary * _Nonnull dataDic) {
        for (NSInteger i=0; i<weakSelf.dataArray.count; i++) {
            NSDictionary *tempDic = weakSelf.dataArray[i];
            NSMutableArray *itemArray = [NSMutableArray arrayWithArray:tempDic[@"items"]];
            if([LGNSString(tempDic[@"category_id"]) isEqualToString:LGNSString(dataDic[@"category_id"])]){
//                [itemArray insertObject:dataDic atIndex:0];
                [itemArray addObject:dataDic];
                [tempDic setValue:itemArray forKey:@"items"];
                [weakSelf.dataArray replaceObjectAtIndex:i withObject:tempDic];
                [weakSelf.tableView reloadData];
                return;
            }
        }
        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
        [tempDic setValue:LGNSString(dataDic[@"category_id"]) forKey:@"category_id"];
        [tempDic setValue:LGNSString(dataDic[@"category_name"]) forKey:@"category_name"];
        NSMutableArray *tempArray = [NSMutableArray array];
        [tempArray addObject:dataDic];
        [tempDic setValue:tempArray forKey:@"items"];
//        [weakSelf.dataArray insertObject:tempDic atIndex:0];
        [weakSelf.dataArray addObject:tempDic];
        [weakSelf.tableView reloadData];
    };
}

//保存
-(void)saveButtonAction{
    NSMutableDictionary *saveDic = [NSMutableDictionary dictionary];
    for (NSInteger i=0; i<4; i++) {
        NSArray *alertArray = @[@"请输入方案名称",@"请输入预估时长",@"请输入频率",@"请输入方案描述"];
        NSArray *placeArray = @[@"请输入方案名称(20字以内)",@"请输入预估时长",@"请输入方案描述(10字以内)",@"请输入方案描述(200字以内)"];
        NSString *key = self.keyDic[[NSString stringWithFormat:@"%ld",i]];
        NSString *content = [self.dataDic.allKeys containsObject:key]?LGNSString(self.dataDic[key]):@"";
        content = [content isEqualToString:placeArray[i]]?@"":content;
        if(i<4 && content.length == 0 ){
            [TooltipView showMessage:alertArray[i] offset:0];
            return;
        }
        [saveDic setValue:content forKey:key];
    }
    if(self.dataArray.count == 0){
        [TooltipView showMessage:@"请添加训练项目" offset:0];
        return;
    }
    [saveDic setValue:self.planid forKey:@"id"];
    [saveDic setValue:[ObjectTool objectToJson:self.dataArray] forKey:@"action_json"];
    [RequestUtil withPOST:@"/doctor/sport.plan/save" parameters:saveDic withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if (code == 200) {
            [TooltipView showMessage:@"保存成功" offset:0];
            if(self.saveDataSuccess){
                self.saveDataSuccess();
            }
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [TooltipView showMessage:message offset:0];
        }
    } error:^(NSError *error) {
        [TooltipView showMessage:@"保存失败，请重试" offset:0];
    }];
}


//编辑内容
-(void)editSportsProgram:(NSString *)type indexPath:(NSIndexPath *)indexPath{
    __block NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:self.dataArray[indexPath.section-5][@"items"][indexPath.row]];
    __block NSInteger section = indexPath.section-5;
    __block NSInteger row = indexPath.row;
    if([type isEqualToString:@"title"]){
        //修改项目title
        LGTrainingProgramController *controller = [[LGTrainingProgramController alloc]init];
        controller.categoryid = LGNSString(tempDic[@"category_id"]);
        controller.dataid = LGNSString(tempDic[@"id"]);
        [self.navigationController pushViewController:controller animated:YES];
        __weak typeof(self) weakSelf = self;
        controller.editTrainingData = ^(NSDictionary * _Nonnull dataDic) {
            NSMutableDictionary *newDic = weakSelf.dataArray[section];
            NSMutableArray *itemArray = [NSMutableArray arrayWithArray:weakSelf.dataArray[section][@"items"]];
            [itemArray replaceObjectAtIndex:row withObject:dataDic];
            [newDic setValue:itemArray forKey:@"items"];
            [weakSelf.dataArray replaceObjectAtIndex:section withObject:newDic];
            [weakSelf.tableView reloadData];
        };
        
    }else if ([type isEqualToString:@"content"]){
        NSString *selectStr = [NSString stringWithFormat:@"%@|%@|%@",tempDic[@"group_times"],tempDic[@"action_times"],tempDic[@"duration"]];
        LGPickerViewMax *pickerView = [[LGPickerViewMax alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
        pickerView.unitOffset = viewPix(30);
        pickerView.pickArry = @[@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10"],@[@"1",@"2",@"3",@"4",@"5",@"6",@"8",@"10",@"12",@"15",@"20",@"25",@"30"],@[@"无",@"5",@"10",@"15",@"20",@"25",@"30",@"40",@"50",@"60",@"80",@"100",@"120"]];
        pickerView.units = @[@"组",@"次",@"秒"];//
        pickerView.selectStr = selectStr;
        [[UIApplication sharedApplication].keyWindow addSubview:pickerView];
        __weak typeof(self) weakSelf = self;
        pickerView.selectPickViewResult = ^(NSArray *resultArray) {
            [tempDic setValue:LGNSString(resultArray[0]) forKey:@"group_times"];
            [tempDic setValue:LGNSString(resultArray[1]) forKey:@"action_times"];
            [tempDic setValue:LGNSString(resultArray[2]) forKey:@"duration"];
            NSMutableDictionary *newDic = weakSelf.dataArray[section];
            NSMutableArray *itemArray = [NSMutableArray arrayWithArray:weakSelf.dataArray[section][@"items"]];
            [itemArray replaceObjectAtIndex:row withObject:tempDic];
            [newDic setValue:itemArray forKey:@"items"];
            [weakSelf.dataArray replaceObjectAtIndex:section withObject:newDic];
            [weakSelf.tableView reloadData];
        };
    }
}

 
//上移、下移
-(void)moveProgramPosition:(NSString *)type indexPath:(nonnull NSIndexPath *)indexPath{
    NSMutableDictionary *tempDic = self.dataArray[indexPath.section-5];
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:tempDic[@"items"]];
    if([type isEqualToString:@"up"]){
        //上移
        [tempArray exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row-1];
    }else{
        //下移
        [tempArray exchangeObjectAtIndex:indexPath.row withObjectAtIndex:indexPath.row+1];
    }
    [tempDic setValue:tempArray forKey:@"items"];
    [self.dataArray replaceObjectAtIndex:indexPath.section-5 withObject:tempDic];
    [self.tableView reloadData];
}

//删除
-(void)removeProgramAction:(NSIndexPath *)indexPath{
    NSDictionary *tempDic = self.dataArray[indexPath.section-5][@"items"][indexPath.row];
    NSString *content = [NSString stringWithFormat:@"您确定要删除%@项目吗？",tempDic[@"title"]];
    __block NSInteger section = indexPath.section;
    __block NSInteger row = indexPath.row;
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"删除运动项目" content:content sureAction:^{
        NSMutableDictionary *mutDic = weakSelf.dataArray[section-5];
        NSMutableArray *tempArray = [NSMutableArray arrayWithArray:mutDic[@"items"]];
        [tempArray removeObjectAtIndex:row];
        if(tempArray.count == 0){
            [weakSelf.dataArray removeObjectAtIndex:section-5];
        }else{
            [mutDic setValue:tempArray forKey:@"items"];
            [weakSelf.dataArray replaceObjectAtIndex:section-5 withObject:mutDic];
        }
        [weakSelf.tableView reloadData];
    }];
}

//文字输入
-(void)inputCellEditingChanged:(NSString *)content section:(NSInteger)section{
    NSString *key = self.keyDic[[NSString stringWithFormat:@"%ld",section]];
    [self.dataDic setValue:content forKey:key];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataArray.count+5;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section<4){
        return 1;
        
    }else if (section > 4){
        NSArray *tempArray = self.dataArray[section-5][@"items"];
        return tempArray.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section<4){
        NSArray *placeArray = @[@"请输入方案名称(20字以内)",@"请输入预估时长",@"请输入频率(10字以内)",@"请输入方案描述(200字以内)"];
        NSArray *lengthArray = @[@"20",@"3",@"10",@"200"];
        LGRecoverySportsInputCell *inputCell = [tableView dequeueReusableCellWithIdentifier:@"InputCell" forIndexPath:indexPath];
        inputCell.selectionStyle = UITableViewCellSelectionStyleNone;
        inputCell.textView.keyboardType = (indexPath.section == 1)?UIKeyboardTypeNumberPad:UIKeyboardTypeDefault;
        inputCell.minHeight = (indexPath.section == 3)?viewPix(96):viewPix(43);
        inputCell.maxLength = [lengthArray[indexPath.section] integerValue];
        inputCell.placeHolder = placeArray[indexPath.section];
        inputCell.section = indexPath.section;
        inputCell.delegate = self;
        NSString *key = self.keyDic[[NSString stringWithFormat:@"%ld",indexPath.section]];
        inputCell.content = [self.dataDic.allKeys containsObject:key]?LGNSString(self.dataDic[key]):@"";
        return inputCell;
        
    }else{
        LGRecoverySportsProgramCell *programCell = [tableView dequeueReusableCellWithIdentifier:@"ProgramCell" forIndexPath:indexPath];
        programCell.selectionStyle = UITableViewCellSelectionStyleNone;
        programCell.indexPath = indexPath;
        NSArray *tempArray = self.dataArray[indexPath.section-5][@"items"];
        programCell.lineView.hidden = (indexPath.row == tempArray.count-1)?YES:NO;
        programCell.dataDic = tempArray[indexPath.row];
        programCell.delegate = self;
        if (tempArray.count == 1) {
            //只有一个
            programCell.position = @"single";
        }else if(indexPath.row == 0){
            //第一个
            programCell.position = @"first";
        }else if (indexPath.row == tempArray.count-1){
            //最后一个
            programCell.position = @"last";
        }else{
            programCell.position = @"middle";
        }
        
        NSInteger count = 0;
        for (NSInteger i=0; i<self.dataArray.count; i++) {
            NSArray *tempArray = self.dataArray[i][@"items"];
            if(i<indexPath.section-5){
                count += tempArray.count;
            }else if (i == indexPath.section-5){
                count+=indexPath.row;
                break;
            }
        }
        programCell.index = count;
        return programCell;
    }
//    else{
//        return nil;
//        if(indexPath.section > 4)
//    }
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section<5){
        return viewPix(32);
        
    }else{
        NSArray *tempArray = self.dataArray[section-5][@"items"];
        CGFloat height = (tempArray.count>0)?viewPix(25):0.01;
        return height;
    }
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section<5){
        NSArray *titleArray = @[@"方案名称",@"时长（分钟）",@"频率",@"描述",@"训练目录"];
        LGRecoverySectionView *sectionView = [[LGRecoverySectionView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(32))];
        sectionView.title = titleArray[section];
        return sectionView;
        
    }else{
        NSDictionary *tempDic = self.dataArray[section-5];
        UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(25))];
        UILabel *titleLabel = [UILabel lableWithText:LGNSString(tempDic[@"category_name"]) colorString:@"#333333" textFont:LGFontWeight(15, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        titleLabel.frame = CGRectMake(viewPix(16), 0, viewPix(150), viewPix(25));
        [sectionView addSubview:titleLabel];
        return sectionView;
        
    }
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
    return view;
}

-(NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableDictionary *)dataDic{
    if(!_dataDic){
        _dataDic = [NSMutableDictionary dictionary];
    }
    return _dataDic;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(84)-bottomSafeBarHeight/2.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGRecoverySportsInputCell class] forCellReuseIdentifier:@"InputCell"];
        [_tableView registerClass:[LGRecoverySportsProgramCell class] forCellReuseIdentifier:@"ProgramCell"];
        _tableView.backgroundColor = [UIColor colorWithString:@"#FFFFFF"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = viewPix(110);
        _tableView.estimatedSectionHeaderHeight = viewPix(32);
        _tableView.estimatedSectionFooterHeight = 0.01;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(110))];
        [footView addSubview:self.addButton];
        _tableView.tableFooterView = footView;
        if(@available(iOS 15.0, *)) {
           _tableView.prefetchingEnabled = NO;
       }
    }
    return _tableView;
}

-(UIButton *)addButton{
    if(!_addButton){
        _addButton = [UIButton buttonWithTitle:@"添加训练" titleFont:LGFont(16) textColor:@"#999999" imageName:@"运动方案-添加训练"];
        _addButton.frame = CGRectMake((Screen_W-viewPix(80))/2.0, viewPix(5), viewPix(80), viewPix(90));
        [_addButton setButtonInsetsStyle:LGButtonInsetsStyleTop marginSpace:5];
        [_addButton addTarget:self action:@selector(addButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addButton;
}

-(UIButton *)saveButton{
    if(!_saveButton){
        _saveButton = [UIButton buttonWithTitle:@"保存" topMargin:kMaxY(self.tableView.frame)+viewPix(12)];
        [_saveButton addTarget:self action:@selector(saveButtonAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveButton;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
